-- UIUserProtocol
-- Create by chengb Oct/13/2015
-- 游戏公告界面

UIUserProtocol = class("UIUserProtocol", function()
    return cc.Layer:create()
end)

function UIUserProtocol.create(title, contentList)
    return UIUserProtocol.new(title, contentList);
end

-- 每行最多可显示的字数
local PER_LINE_WORD_COUNT = 28;

-- 默认的标题和内容
local defaultTitle   = "User agreement";
local defaultContent = "This is a user agreement";

-- 构造函数
function UIUserProtocol:ctor(title, contentList)
    self:setName("UIUserProtocol");

    -- 初始化
    local node = cc.CSLoader:createNode("layout/login/UserProtocol.csb");
    self:addChild(node);
    self.node = node;

    -- 记录用户协议信息
    if getLang() ~= "zh" then
        -- 目前用户协议仅支持简体中文版
        self.title = defaultTitle;
        self.contentList = { defaultContent };
    else
        self.title       = title;
        self.contentList = contentList;
    end

    -- 初始化窗口
    self:initForm();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 适配
    self:resize();

    -- 标记显示过用户协议
    _G["hasShowUserProtocol"] = true;
end

-- 初始化窗口
function UIUserProtocol:initForm()
    -- 标题
    local titleLabel = findChildByName(self.node, "CT/title");
    titleLabel:setString(self.title);
    TextStyleM.setSubheadStyle(titleLabel);

    -- 先显示第一部分内容，其他的等滚到底部时再显示
    self.curPartIndex = 1;
    local content = self:getContentByPart(self.curPartIndex);

    local scrollview = findChildByName(self.node, "CT/scroll_view");
    scrollview.contentChildList = {};
    self.scrollview = scrollview;

    self:attachContent(content);
end

-- 添加滚动条
function UIUserProtocol:attachIndicator()
    local scrollview = self.scrollview;

    -- 滚动容器到达底部时的回调
    local function pageCallback()
        if self.curPartIndex >= #self.contentList then
            -- 已经到最后一页了
            return;
        end

        local curTime = TimeM.getCurrentTime();
        if self.lastLoadingTime and curTime - self.lastLoadingTime < 1 then
            -- 加载冷却中
            -- trace("UIUserProtocol", "加载冷却中...");
            return;
        end

        self.loadingIndex = self.curPartIndex + 1;
        self.lastLoadingTime = curTime;

        trace("UIUserProtocol", "---------------显示第%d部分", self.loadingIndex);

        -- 显示下一部分内容
        local nextContent = self:getContentByPart(self.loadingIndex);
        self:attachContent(nextContent);
        self.curPartIndex = self.curPartIndex + 1;
    end

    -- 添加滚动条
    if self.indicator then
        scrollview:getParent():removeChild(self.indicator);
        ScrollTool.removeEventListener(scrollview);
    end
    UIIndicator.attach(scrollview, true, pageCallback);
    local indicator = scrollview:getParent():getChildByName("UIIndicator");
    indicator:setPositionX(indicator:getPositionX() + 2);
    self.indicator = indicator;
end

-- 为滚动容器附加内容
function UIUserProtocol:attachContent(content)
    local scrollview = self.scrollview;

    local contentLabel = ccui.Text:create();
    contentLabel:setAnchorPoint(0, 1);

    local locFix = 1;
    TextStyleM.setTextStyle(contentLabel, TextStyleM.TEXT_SIZE_TINY2,
        TextStyleM.TEXT_COLOR_DARK_BROWN, false, -1, nil, nil, PER_LINE_WORD_COUNT / locFix);

    -- 设置行间距和内容，用于计算高度
    contentLabel:getVirtualRenderer():setLineHeight(TextStyleM.TEXT_LINE_HIGHT_MIDDLE);
    contentLabel:setString(content);

    -- 添加文本变色效果
    -- TODO 目前applyString这个函数有个bug：在一个页面不能有多个label执行applyString，否则显示会异常
    -- 为了解决这个问题，这里将label放在一个layout里面
    contentLabel = applyString(contentLabel, content, nil, nil, TextStyleM.TEXT_LINE_HIGHT_MIDDLE);
    local layout = ccui.Layout:create();
    local contentSize = getRealContentSize(contentLabel);
    layout:setAnchorPoint(0, 1);
    layout:setContentSize(cc.size(contentSize.width, contentSize.height));
    contentLabel:setPosition(cc.p(0, contentSize.height));
    layout:addChild(contentLabel);
    scrollview:addChild(layout);
    table.insert(scrollview.contentChildList, layout);

    -- 重新排布
    self:relayoutScrollview();
end

-- 重新排布滚动容器
function UIUserProtocol:relayoutScrollview()
    local scrollview = self.scrollview;
    local childList  = scrollview.contentChildList;

    -- 最上方的文本与滚动容器的上边距
    local marginTop = 15;

    -- 文本与滚动容器的左边距
    local marginLeft = 8;

    -- 计算滚动容器总高度
    local totalHeight = marginTop;
    for i = 1, #childList do
        local contentLayout = childList[i];
        totalHeight = totalHeight + getRealContentSize(contentLayout).height;
    end
    totalHeight = math.max(totalHeight, scrollview:getInnerContainerSize().height);

    -- 设置第一个文本的坐标
    local posX = marginLeft;
    local startPosY = totalHeight - marginTop;
    local contentLayout = scrollview.contentChildList[1];
    contentLayout:setPosition(cc.p(posX, startPosY));

    -- 上一个文本的坐标
    local prePosY = startPosY;

    for i = 2, #childList do
        local curLayout = childList[i];
        local preLayout = childList[i - 1];
        local curPosY = prePosY - getRealContentSize(preLayout).height;
        curLayout:setPosition(cc.p(posX, curPosY));
        prePosY = curPosY;
    end

    scrollview:setInnerContainerSize(cc.size(scrollview:getInnerContainerSize().width, totalHeight));

    -- 添加滚动条
    self:attachIndicator();
end

-- 获取指定部分的内容
function UIUserProtocol:getContentByPart(partIndex)
    if partIndex < 1 or partIndex > #self.contentList then
        -- 已经是最后一部分了
        return nil;
    end

    return self.contentList[partIndex];
end

-- 注册点击事件
function UIUserProtocol:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 直接关闭应用
            exitApp();
        end
    end
    btnBack:addTouchEventListener(onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getCoreLocStr("btn_text_refuse"));

    -- 注册同意按钮点击事件
    local btnAgree = findChildByName(self.node, "BT/btn_agree");
    local function onAgreeClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            self:agreeProtocol();
        end
    end
    btnAgree:addTouchEventListener(onAgreeClick);
    TextStyleM.setTextStyle(btnAgree, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnAgree:setTitleText(getCoreLocStr("btn_text_agree"));
end

-- 同意协议的处理
function UIUserProtocol:agreeProtocol()
    _G["gameScene"]:removeFormByName("UIUserProtocol");

    UserProtocolM.agreeUserProtocol();

    -- 开始自动更新
    clearMyRequire();
    enterAutoPatchScene();
end

-- 注册事件处理回调函数
function UIUserProtocol:registerEventCallback()
    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UIUserProtocol 界面析构清理");
        end
    end);
end

-- 适配
function UIUserProtocol:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end
